from llmtcg.agents.base import Agent
from llmtcg.chat.model import ChatContext

from dataclasses import dataclass, field
from typing import List, Tuple
from tempfile import mkstemp
from subprocess import run, PIPE, CompletedProcess
from os import path


@dataclass
class TestSceneGeneratingAgent(Agent):

    @property
    def system_prompt(self) -> str:
        return """
        You are an experienced test engineer. You are supposed to generate test scenes
        according to the given requirements.

        The test scearios should include the functional testing, error handling testing and
        cooperation with other linux kernel APIs.

        In the output, test scenes should be separated by a separating line "======".

        Each test scene should be formatted as described as follows:

        - The first line (which should be after the separating line) is
          "Test Scene {name}" where the name should be a very brief description
          of what this test scene does,
        - Then you should give the goal of this test case,
        - After the goal, you should give very detailed steps describing how we should
          perform this test scene,
        - Finally you need to show what is the expected result of this test scene.

        To be noticed, if successfully running this test scene requires other preparation
        works (e.g. to create a file, or to start a socket server), then you also need to put
        them into the steps of this test scene.

        Each test scene should be minimized and only focus on the functionality it tests. DO
        NOT mix multiple test scenes in a single one.
        """

    def generate_test_scene(self, requirement: str) -> List[str]:
        chat_context = ChatContext(self.chat_model)
        chat_context.system_prompt = self.system_prompt
        chat_context.task_identifier = "TestSceneGeneration::generateTestScene"

        scenes: List[str] = []
        resp = chat_context.chat(requirement)

        blocks: List[str] = [""]
        for line in resp.splitlines():
            if all((c == '=' for c in line)):
                # this line is an separator
                blocks.append("")
            else:
                blocks[-1] += line + "\n"

        for block in blocks:
            block = block.strip()
            if block.startswith("Test Scene"):
                scenes.append(block)

        if len(scenes) == 0:
            print(resp)
            raise Exception(f"cannot extract any test scene")

        return scenes
